import 'dart:io';

import 'package:cgvc/basis/view_state.dart';
import 'package:cgvc/helper/string_helper.dart';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:oktoast/oktoast.dart';

class BasisViewModel extends ChangeNotifier {
  ViewState _viewState;

  ViewStateError _viewStateError;

  BasisViewModel({ViewState viewState})
      : _viewState = viewState ?? ViewState.success;

  ViewState get viewState => _viewState;

  set viewState(ViewState viewState) {
    _viewStateError = null;
    _viewState = viewState;
    notifyListeners();
  }

  ViewStateError get viewStateError => _viewStateError;

  String get errorMessage => viewStateError?.message;

  bool get loading => viewState == ViewState.loading;

  bool get success => viewState == ViewState.success;

  bool get empty => viewState == ViewState.empty;

  bool get error => viewState == ViewState.error;

  void setSuccess() {
    viewState = ViewState.success;
  }

  void setLoading() {
    viewState = ViewState.loading;
  }

  void setEmpty() {
    viewState = ViewState.empty;
  }

  //未授权回调
  void onUnAuthorizedException() {}

  //方法参数体未声明类型，就是动态类型dynamic
  void setError(e, stackTrace, {String message}) {
    ErrorType errorType = ErrorType.normal;
    if (e is DioError) {
      e = e.error;
      if (e is HttpException) {
        stackTrace = null;
        message = e.message;
      } else {
        errorType = ErrorType.network;
      }
    }
    viewState = ViewState.error;
    _viewStateError =
        ViewStateError(errorType, message: message, errorMessage: e.toString());
    printErrorStack(e, stackTrace);
  }

  showErrorMessage(context, {String message}) {
    if (viewStateError != null && message != null) {
      if (viewStateError.isNetWorkError) {
        message ??= StringHelper.getS().viewStateNetworkError;
      } else {
        message ??= viewStateError.message;
      }

      Future.microtask(() => showToast(message, context: context));
    }
  }

  printErrorStack(e, s) {
    debugPrint('''
    <-----↓↓↓↓↓↓↓↓↓↓-----error-----↓↓↓↓↓↓↓↓↓↓----->
    $e    
    <-----↑↑↑↑↑↑↑↑↑↑-----error-----↑↑↑↑↑↑↑↑↑↑----->
    ''');

    if (s != null) {
      debugPrint('''
      <-----↓↓↓↓↓↓↓↓↓↓-----trace-----↓↓↓↓↓↓↓↓↓↓----->
      $s
      <-----↑↑↑↑↑↑↑↑↑↑-----trace-----↑↑↑↑↑↑↑↑↑↑----->
      ''');
    }
  }
}
